import React, { useEffect, useState } from "react";
import { Button, Col, Form, Input, InputNumber, DatePicker, Select, Flex, Row, Collapse, Tooltip } from "antd";
import { useTranslation } from 'react-i18next';
import { DownOutlined, UpOutlined, DeleteOutlined, CopyOutlined } from '@ant-design/icons';
import { DROPDOWN, TEXTINPUT, NUMBERINPUT, TEXTAREA, DATEPICKER, ATTACHMENT, ACCEPT_TYPE, DATEFORMAT, APPROVAL_STATUS, RES_MODE } from '../../../utils/constant';
import { transformArray, resquestDetialAttachmentListFormat } from "../../../utils/commonUtil";
import DeleteConfirm from '../DeleteConfirm';
import RequestUploadItem from '../RequestUploadItem';
import './index.scss';
import _ from 'lodash';
import { apiSysTemplateInitiate } from '../../../services/common';

const RequestFormProductTpl = ({
  listNames,
  form,
  initialValues,
  uploadParams,
  productExtraContentrRender,
  editMode,
  moduleConfig,
}) => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const [expandIndexList, setExpandIndexList] = useState(editMode === RES_MODE.NEW ? ['1'] : ['1', '2', '3']);
  // const [addIndex, setAddIndex] = useState([]);
  const projectNotDynamicRenderKey = [
    'approveBy',
    'approveTargetType',
    'buType',
    'createdBy',
    'createdTime',
    'moduleName',
    'requestStatus',
    'synTouchProjectId',
    'synTouchProductId',
    'synTouchProductName',
    'attachmentMd5',
    'templateName',
    'updatedBy',
    'updatedTime',
    'attachmentUrl',
    'entry',
    'productName',
    'searchRequestProductId',
    'searchRequestProjectId',
    'bigFileProjectId',
    'bigFileProductId',
    'experimentalProjectId',
    'experimentalProductId',
    'components',
    'productAttachmentUrl',
    'testMethodAttachmentUrl',
    'analysisContents',
  ];
  const initRenderData = editMode === RES_MODE.NEW ? {
    ...initialValues,
    [listNames]: [
      {
        // productName 为固定字段
        productName: {
          fieldOptionValue: '',
          fieldValue: '',
          fieldType: "Text Input",
          isRequired: '1'
        },
        ...initialValues?.[listNames]?.[0]
      }
    ]
  } :
    {
      [listNames]: initialValues?.[listNames]?.map((item) => {
        return {
          productName: {
            fieldOptionValue: '',
            fieldValue: item?.productName?.fieldValue,
            fieldType: "Text Input",
            isRequired: '1'
          },
          ...item,
        }
      })
    };
  const [renderData, setRenderData] = useState(initRenderData);
  const [tplData, setTplData] = useState(editMode === RES_MODE.NEW ? initRenderData : {});
  // console.log(initRenderData);
  // console.log('~~~~~~~~~~');
  const { t } = useTranslation();
  const { TextArea } = Input;

  const onChangeDatePicker = (date, dateString) => {
    // console.log(date, dateString);
  };
  // product copy
  const copyListItemHandle = (index) => {
    let updateProductListData = form?.getFieldsValue()?.[listNames];
    const copyItemData = _.cloneDeep(_.omit(updateProductListData?.[index], projectNotDynamicRenderKey));
    // 不copy附件
    for (let key in copyItemData) {
      copyItemData[key].fieldValue = copyItemData?.[key]?.fieldType === ATTACHMENT ? '' : copyItemData?.[key]?.fieldValue
    };
    const productItemData = {
      productName: {
        fieldOptionValue: '',
        fieldValue: '',
        fieldType: "Text Input",
        isRequired: '1'
      },
      ...copyItemData,
    };
    updateProductListData = [...updateProductListData, productItemData];
    form.setFieldsValue({
      [listNames]: updateProductListData,
    });
    setRenderData({
      ...form?.getFieldsValue().Project,
      [listNames]: updateProductListData,
    });
  };
  // 删除product
  const delListItemHandle = (remove, index) => {
    DeleteConfirm({
      t,
      title: t('common.deleteMsg'),
      onOk () {
        let updateProductListData = form?.getFieldsValue()?.[listNames];
        updateProductListData?.splice(index, 1);
        setRenderData(updateProductListData);
        form.setFieldsValue({
          [listNames]: updateProductListData,
        });
      }
    });
  };
  const tplDataAsync = async () => {
    let tplIdData = [];
    if (editMode === RES_MODE.EDIT) {
      const params = {
        templateName: initialValues?.project?.templateName?.fieldValue,
        buType: initialValues?.project?.buType?.fieldValue,
        moduleName: initialValues?.project?.moduleName?.fieldValue,
      };
      const initTplData = await apiSysTemplateInitiate(params);
      if (initTplData?.data?.code === 200) {
        setTplData({
          project: initTplData?.data?.data?.Project,
          product: [
            {
              productName: {
                fieldOptionValue: '',
                fieldValue: '',
                fieldType: "Text Input",
                isRequired: '1'
              },
              ...initTplData?.data?.data?.Product,
            }
          ]
        });
      }

    };
  };
  useEffect(() => {
    tplDataAsync();
  }, [initialValues]);
  useEffect(() => {
    form.setFieldsValue({
      [listNames]: {
        ...renderData
      },
    });
  }, [renderData]);
  return (
    <div className='request-prod-wrap'>
      {form &&
        <Form.List name={listNames}>
          {(fields, { add, remove }) => (
            <div key={fields.key}>
              <Collapse
                collapsible='icon'
                activeKey={expandIndexList}
                onChange={(val) => {
                  setExpandIndexList([...val])
                }}
                expandIcon={({ isActive, index }) => (
                  <span className="expan-icon">
                    {
                      isActive ? <UpOutlined style={{ fontSize: 18, color: '#666666' }} /> :
                        <DownOutlined style={{ fontSize: 18, color: '#666666' }} />
                    }
                  </span>
                )}
                expandIconPosition='end'
                items={fields.map((field, index) => {
                  const listData = renderData?.[listNames]?.[index] ? renderData?.[listNames]?.[index] : tplData?.[listNames]?.[0];
                  return (
                    {
                      key: Number(index) + 1,
                      label: (
                        <Flex justify="space-between" align="center">
                          <div>{'Entry ' + (Number(index) + 1)}</div>
                          <div>
                            <Tooltip title={t('common.delete')}>
                              <Button
                                type="text"
                                icon={<DeleteOutlined style={{ fontSize: 18, color: '#b14124', }} />}
                                onClick={() => {
                                  delListItemHandle(remove, field.name);
                                  setExpandIndexList([...expandIndexList.filter(item => item !== (Number(index) + 1))]);
                                }}
                              />
                            </Tooltip>
                            <Tooltip title={t('common.copy')}>
                              <Button
                                type="text"
                                icon={<CopyOutlined style={{ fontSize: 18 }} />}
                                onClick={() => {
                                  copyListItemHandle(index);
                                  setExpandIndexList([...expandIndexList, String(form?.getFieldsValue()?.[listNames]?.length)]);
                                }}
                              />
                            </Tooltip>
                          </div>
                        </Flex>
                      ),
                      children: <Row gutter={[24, 0]} key={`collapse-row-${fields.key}`}>
                        {/* 保证productName位置，单独渲染 */}
                        <Col span={6}>
                          <Form.Item
                            initialValue={listData?.productName?.fieldValue}
                            labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }}
                            label={t('requestDetails.productName')}
                            name={[field.name, 'productName', 'fieldValue']}
                            rules={[
                              {
                                required: true,
                                message: t('common.isRequired'),
                              }
                            ]}>
                            <Input placeholder={t('common.pleaseEnter')} />
                          </Form.Item>
                          <Form.Item name={[field.name, 'productName', 'fieldOptionValue']} initialValue={index + 1} hidden></Form.Item>
                          <Form.Item name={[field.name, 'productName', 'fieldType']} initialValue={TEXTINPUT} hidden></Form.Item>
                          <Form.Item name={[field.name, 'productName', 'isRequired']} initialValue={1} hidden></Form.Item>
                          <Form.Item name={[field.name, 'productName', 'entry']} initialValue={index + 1} hidden></Form.Item>
                        </Col>
                        {
                          // 保证productName位置，单独渲染
                          listData && Object.keys(listData)?.filter(name => name !== 'productName')?.map((key) => {
                            const itemData = listData?.[key];
                            const labelName = key;
                            const itemType = itemData?.fieldType;
                            const itemValues = itemData?.fieldValue;
                            const optionValues = itemData?.fieldOptionValue;
                            const itemRequired = itemData?.isRequired === '1' ? true : false;
                            const itemRequiredInt = itemData?.isRequired;
                            const fileList = itemData?.fieldType === ATTACHMENT && resquestDetialAttachmentListFormat(itemData?.fieldValue);
                            return (
                              <>
                                {itemType === DROPDOWN || itemType === TEXTINPUT || itemType === NUMBERINPUT || itemType === DATEPICKER ?
                                  <Col span={6} style={{ display: projectNotDynamicRenderKey?.includes(key) && 'none' }}>
                                    <Form.Item
                                      initialValue={itemValues}
                                      {...field}
                                      labelCol={{ span: 24 }}
                                      wrapperCol={{ span: 24 }}
                                      label={labelName}
                                      name={[field.name, key, 'fieldValue']}
                                      rules={[
                                        {
                                          required: itemRequired,
                                          message: t('common.isRequired'),
                                        },
                                      ]}>
                                      {
                                        itemType === TEXTINPUT &&
                                        <Input placeholder={t('common.pleaseEnter')} />
                                      }
                                      {
                                        itemType === NUMBERINPUT &&
                                        <InputNumber placeholder={t('common.pleaseEnter')} style={{ width: '100%' }} />
                                      }
                                      {
                                        itemType === DROPDOWN &&
                                        <Select placeholder={t('common.pleaseSelect')} options={transformArray(optionValues)} mode='multiple' />
                                      }
                                      {
                                        itemType === DATEPICKER &&
                                        <DatePicker placeholder={t('common.pleaseSelect')} format={DATEFORMAT} onChange={onChangeDatePicker} style={{ width: '100%' }} />
                                      }
                                    </Form.Item>
                                  </Col>
                                  :
                                  <Col span={24} style={{ display: projectNotDynamicRenderKey?.includes(key) && 'none' }}>
                                    {/* 单个占一行 */}
                                    <Form.Item
                                      initialValue={itemValues}
                                      {...field}
                                      labelCol={{ span: 24 }}
                                      wrapperCol={{ span: 24 }}
                                      label={labelName}
                                      name={[field.name, key, 'fieldValue']}
                                      rules={[
                                        {
                                          required: itemRequired,
                                          validator: async (rule, value) => {
                                            if (!value && itemRequired) {
                                              return Promise.reject(t('common.isRequired'));
                                            } else {
                                              return Promise.resolve();
                                            }
                                          }
                                        }
                                      ]} >
                                      {
                                        itemType === TEXTAREA &&
                                        <TextArea placeholder={t('common.pleaseEnter')} />
                                      }
                                      {
                                        itemType === ATTACHMENT &&
                                        <RequestUploadItem
                                          btnText={t('common.attachment')}
                                          acceptType={ACCEPT_TYPE.ALL}
                                          uploadUpdateFn={({ fileList, deleteFileList }) => {
                                            const updateProductItemData = form?.getFieldsValue()?.[listNames]?.[index];
                                            if (updateProductItemData[key]) {
                                              updateProductItemData[key]['fieldValue'] = fileList;
                                              updateProductItemData[key]['fieldDeleteValue'] = deleteFileList;
                                              // form?.setFieldValue(listNames, updateProductItemData);
                                              form.setFieldsValue({
                                                [listNames]: updateProductItemData,
                                              });
                                              form.validateFields([listNames]);
                                            };
                                          }}
                                          fileListData={fileList}
                                        />
                                      }
                                    </Form.Item>
                                  </Col>
                                }
                                <Form.Item name={[field.name, key, 'fieldOptionValue']} initialValue={index + 1} hidden></Form.Item>
                                <Form.Item name={[field.name, key, 'fieldType']} initialValue={itemType} hidden></Form.Item>
                                <Form.Item name={[field.name, key, 'isRequired']} initialValue={itemRequiredInt} hidden></Form.Item>
                                <Form.Item name={[field.name, key, 'entry']} initialValue={index + 1} hidden></Form.Item>
                              </>
                            )
                          })
                        }
                        {/* product 特殊业务 */}
                        {
                          initialValues?.project?.requestStatus?.fieldValue === APPROVED && productExtraContentrRender &&
                          productExtraContentrRender(index)
                        }
                      </Row>
                    }
                  )
                })}
              />
              <Button onClick={() => {
                add();
                // setAddIndex([...addIndex, form?.getFieldsValue()?.[listNames]?.length - 1]);
                if (editMode === RES_MODE.EDIT || editMode === RES_MODE.NEW) {
                  setExpandIndexList([...expandIndexList, String(form?.getFieldsValue()?.[listNames]?.length)]);
                };
              }} >{t('common.add')}</Button>
            </div>
          )}

        </Form.List>
      }
    </div>
  )
};

export default RequestFormProductTpl;

